package com.samphanie.auiu.auth.security.components;

import cn.hutool.json.JSONUtil;
import com.samphanie.auiu.common.utils.ApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author ZSY
 * @email 1451691457@qq.com
 */
@Slf4j
@Component
public class CodeAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Cache-Control", "no-cache");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        log.error("验证码校验失败: {}", e.getMessage());
        response.getWriter().write(JSONUtil.toJsonStr(ApiResponse.forbidden(e.getMessage())));
        response.getWriter().flush();
    }
}
